package com.ruoyi.web.controller.pay;

import com.google.gson.Gson;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.OrderStatus;
import com.ruoyi.common.enums.PayType;
import com.ruoyi.common.enums.RightType;
import com.ruoyi.common.enums.WxPayState;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.GwEnterpriseInfo;
import com.ruoyi.system.domain.GwPlatformRights;
import com.ruoyi.system.domain.GwPlatformRightsOrder;
import com.ruoyi.system.domain.GwPlatformServiceOrder;
import com.ruoyi.system.domain.vo.WxPayResultVO;
import com.ruoyi.system.mapper.GwPlatformRightsOrderMapper;
import com.ruoyi.system.service.*;
import com.ruoyi.system.utils.HttpUtils;
import com.wechat.pay.contrib.apache.httpclient.auth.Verifier;
import io.swagger.annotations.Api;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @ProjectName: back
 * @Package: com.ruoyi.web.controller.pay
 * @ClassName: WechatPayController
 * @Author: haiyue
 * @Description:
 * @Date: 2025/6/5 下午 6:03:36
 * @Version: 1.0
 */

@Api(description = "微信支付")
@RestController
@RequestMapping("/api/wechat")
public class WechatPayController {
    private static final Logger log = LoggerFactory.getLogger(WechatPayController.class);

    @Autowired
    private  WechatPayConfig wxPayUserConfig;
    @Autowired
    private  Verifier getUserVerifier;
    @Autowired
    private IGwPlatformRightsOrderService rightsOrderService;
    @Autowired
    private IGwPlatformServiceOrderService serviceOrderService;
    @Autowired
    private WeChatPayService weChatPayService;

    /**
     * 微信支付结果通知回调接口
     *
     * @param request HTTP请求对象
     * @return 返回给微信的处理结果
     */
    @PostMapping("/platformRights/notify")
    public Map<String, Object> platformRightsPayNotify(HttpServletRequest request) {
        {
            log.info("收到平台权益微信支付通知回调");
            Gson gson = new Gson();
            try {
                //处理通知参数
                String body = HttpUtils.readData(request);
                Map<String, Object> bodyMap = gson.fromJson(body, HashMap.class);
                String requestId = (String) bodyMap.get("id");
                log.info("平台权益支付通知的id ===> {}", requestId);
                //签名的验证
                if (!wxPayUserConfig.notificationHandler(request, getUserVerifier, body)) {
                    log.error("通知验签失败");
                    //失败应答
                    return buildFailResponse();
                }

                log.info("平台权益通知验签成功");
                //TODO 需要添加重复处理机制
                WxPayResultVO wxPayResultVO = wxPayUserConfig.analyzingWxPayResult(body);

                rightsOrderService.handleRightsOrder(wxPayResultVO);

                return buildSuccessResponse();

            } catch (Exception e) {
                e.printStackTrace();
                return buildFailResponse();
            }
        }
    }

    /**
     * 微信小程序支付结果通知回调接口
     *
     * @param request HTTP请求对象
     * @return 返回给微信的处理结果
     */
    @PostMapping("/platformService/notify")
    public Map<String, Object> platformServicePayNotify(HttpServletRequest request) {
        {
            log.info("收到平台服务微信支付通知回调");
            Gson gson = new Gson();
            try {
                //处理通知参数
                String body = HttpUtils.readData(request);
                Map<String, Object> bodyMap = gson.fromJson(body, HashMap.class);
                String requestId = (String) bodyMap.get("id");
                log.info("平台服务微信支付通知的id ===> {}", requestId);
                //签名的验证
                if (!wxPayUserConfig.notificationHandler(request, getUserVerifier, body)) {
                    log.error("平台服务通知验签失败");
                    //失败应答
                    return buildFailResponse();
                }

                log.info("平台服务通知验签成功");

                WxPayResultVO wxPayResultVO = wxPayUserConfig.analyzingWxPayResult(body);
                if(wxPayResultVO!=null && wxPayResultVO.getTradeState().equals(WxPayState.SUCCESS.getCode())){
                   GwPlatformServiceOrder serviceOrder = serviceOrderService.selectGwPlatformServiceOrderById(wxPayResultVO.getOutTradeNo());
                    serviceOrder.setPayType(PayType.WEI_XIN.getCode());
                    serviceOrder.setPayTime(DateUtils.parseDate(wxPayResultVO.getSuccessTime()));
                    serviceOrder.setStatus(OrderStatus.PAY.getCode());
                    serviceOrder.setTransactionId(wxPayResultVO.getTransactionId());
                    serviceOrderService.updateOrder(serviceOrder);
                }

                return buildSuccessResponse();

            } catch (Exception e) {
                e.printStackTrace();
                return buildFailResponse();
            }
        }
    }

    @GetMapping(value = "/{transactionId}")
    public AjaxResult getWxOrderInfoByTransactionId(@PathVariable("transactionId") String transactionId) throws Exception {

        return weChatPayService.selectWxOrderDetail(transactionId);
    }


    /**
     * 构建成功响应
     *
     * @return 成功响应
     */
    private Map<String, Object> buildSuccessResponse() {
        Map<String, Object> response = new HashMap<>(2);
        response.put("code", "SUCCESS");
        response.put("message", "成功");
        return response;
    }

    /**
     * 构建失败响应
     *
     * @return 失败响应
     */
    private Map<String, Object> buildFailResponse() {
        Map<String, Object> response = new HashMap<>(2);
        response.put("code", "FAIL");
        response.put("message", "失败");
        return response;
    }

}
